package finger.service.impl;

import finger.dao.OrderDao;
import finger.dao.OrderItemDao;
import finger.dao.impl.OrderDaoImpl;
import finger.dao.impl.OrderItemDaoImpl;
import finger.domain.*;
import finger.service.BookService;
import finger.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookService bookService = new BookServiceImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        orderDao.saveOrder(order);
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            CartItem value = entry.getValue();
            OrderItem orderItem = new OrderItem(null, value.getName(), value.getCount(), value.getPrice(), value.getTotalPrice(), orderId);
            orderItemDao.saveOrderItem(orderItem);
            Book book = bookService.queryBookById(value.getId());
            book.setSales(book.getSales() + value.getCount());
            book.setStock(book.getStock() - value.getCount());
            bookService.updateBook(book);
        }
        cart.clear();
        return orderId;
    }

    @Override
    public List<Order> myOrders(int id) {
        return orderDao.queryMyOrders(id);
    }

    @Override
    public List<OrderItem> orderDetails(String orderId) {
        return orderItemDao.queryItemDetailsByOrderId(orderId);
    }

    @Override
    public List<Order> queryAllOrders() {
        return orderDao.queryAllOrders();
    }

    @Override
    public void sendOrder(String orderId) {
        orderDao.changeOrderStatus(1, orderId);
    }

    @Override
    public void receiveOrder(String orderId) {
        orderDao.changeOrderStatus(2, orderId);
    }
}
